import com.amazon.trietree.db.PostgreUtils;
import com.amazon.trietree.server.MetaDataServerID;
import com.amazon.trietree.zkStub.CuratorClientFactory;
import com.amazon.trietree.zkStub.CuratorClientStub;
import com.amazon.trietree.zkStub.CuratorLeaderSelector;
import com.netflix.curator.framework.CuratorFramework;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Tylaar
 * Date: 11/9/12
 * Time: 2:06 PM
 * Company: Amazon.com
 */
public class TestMasterSelection {
    @Test
    public void testMasterSelection()throws Exception{
        String namespace = "dedup";
        String regPath = "/registration";
        String lockPath = "/lock";
        int retryTimes = 100;
        int retryMargin = 1000;
        int timeout = 5000;
        String zkAddress ="162.105.146.28:2181";


        List<CuratorClientStub> stubs = new ArrayList<CuratorClientStub>();
        List<CuratorLeaderSelector> selectors = new ArrayList<CuratorLeaderSelector>();
        List<MetaDataServerID> ids = new ArrayList<MetaDataServerID>();

        try {
            for(int i = 0 ; i < 5 ; i++){
                MetaDataServerID id = new MetaDataServerID(getSeqId().toString());
                CuratorClientStub stub = new CuratorClientStub();
                CuratorFramework client = CuratorClientFactory.createCuratorClientFactory(zkAddress,namespace,timeout,retryTimes,retryMargin);
                CuratorLeaderSelector selector = new CuratorLeaderSelector(client, lockPath, id.getPersonalID());
                stub.setClientStub(client);
                stub.setId(id);
                stub.setLeaderSelector(selector);
                stub.setRegDirectory(regPath);
                stubs.add(stub);
                stub.init();
            }

            for(CuratorClientStub stub: stubs){
                stub.competeForMaster();
            }

            System.out.println("Press enter/return to quit\n");
            new BufferedReader(new InputStreamReader(System.in)).readLine();
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            System.out.println("shutting down...");
            for(CuratorClientStub stub: stubs){
                stub.stopCompeteForMaster();
                stub.destroy();
            }
        }

    }

    public Long getSeqId(){
        PostgreUtils utils = new PostgreUtils();
        utils.setDbLocation("jdbc:postgresql://162.105.146.28/yyfdb");
        utils.setPassword("1988219");
        utils.setUsername("yyf");
        long result = utils.getNextVal();
        return result;
    }
}
